package com.hmall.item.listeners;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.common.constants.MqConstants;
import com.hmall.item.domain.dto.ItemDocDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.hmall.common.constants.MqConstants.*;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/8/14 17:24
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MqListener {
    private final IItemService itemService;
    private final RestHighLevelClient client;

    /**
     * 监听商品上架消息
     * @param itemId 商品ID
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = ITEM_UP_QUEUE, durable = "true"),
            exchange = @Exchange(name = ITEM_EXCHANGE),
            key = ITEM_UP_KEY
    ))
    public void listenerItemUpMsg(Long itemId) throws IOException {
        log.info("接收到商品上架消息，商品ID：{}",itemId);
        // 0、准备数据（数据库）
        Item item = itemService.getById(itemId);
        ItemDocDTO itemDocDTO = BeanUtil.toBean(item, ItemDocDTO.class);

        // 1、创建新增文档请求对象
        IndexRequest request = new IndexRequest("items").id(itemDocDTO.getId().toString());

        // 2、设置文档内容
        request.source(JSONUtil.toJsonStr(itemDocDTO), XContentType.JSON);

        // 发起请求，新增文档
        client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 监听商品下架消息
     * @param itemId 商品ID
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = ITEM_DOWN_QUEUE, durable = "true"),
            exchange = @Exchange(name = ITEM_EXCHANGE),
            key = ITEM_DOWN_KEY
    ))
    public void listenerItemDownMsg(Long itemId) throws IOException {
        log.info("接收到商品下架消息，商品ID：{}",itemId);
        // 1、创建删除文档请求对象
        DeleteRequest request = new DeleteRequest("items",itemId.toString());

        // 2、发起删除请求
        client.delete(request,RequestOptions.DEFAULT);
    }
}
